const express = require('express')
const app = express()
const server = require('http').createServer(app)
const bodyParser = require('body-parser')
const chatServer = require('./lib/chat_server')

// 设置body-parser中间件
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

//使用ejs模板引擎   默认找views这个目录
app.set('view engine', 'ejs')

//配置public目录为我们的静态资源目录
app.use(express.static('public'))

app.use((req, res, next) => {
  if (req.url === '/') {
    res.redirect('/login')
  } else {
    next()
  }
})

app.get('/login', (req, res) => {
  res.render('login')
})

app.post('/chat', (req, res) => {
  let username = req.body.username
  app.locals['username'] = username
  res.render('chat')
})
chatServer.listen(server)
server.listen(3005, '127.0.0.1', () => {
  console.log('Server is running at http://localhost:3005')
})
